import _ from 'love-u'
import config from './config'
import { $getToken, $clearLoginInfo } from './storage'
import { $redirect2Login } from './router'
import { $msg } from './message'


function $request({ method, url, needAuth, header, data }) {
    return new Promise((resolve, reject) => {
        if (!url.startsWith("http")) url = config.BASE_API + url;
        console.log("simba:访问了" + url);
        header = header || {};
        // 需要传token去识别身份
        if (needAuth) {
            let access_token = $getToken();
            if (access_token) header[config.KEY_TOKEN] = access_token;
            else {
                return $msg("请先登录", () => {
                    $clearLoginInfo()
                    resolve({ success: false });
                    $redirect2Login();
                });
            }
        }

        uni.request({
            method,
            url,
            data,
            header,
            success: ({ data, statusCode }) => {
                if (!data) data = { errorCode: 200, data: null, message: "" };
                //网络500
                if (statusCode === 200) resolve(data);
                else reject(statusCode);
                //业务系统500
                switch (data.errorCode) {
                    case 500:
                        // $msg(data.message || "网络异常,请稍后再试");
                        reject(data.errorCode);
                        break;
                    case 4001:
                    case 40001:
                    case 401:
                        $msg("登录超时，请重新登录", () => {
                            $clearLoginInfo()
                            reject({ success: false });
                            $redirect2Login();
                        });
                }
            },
            fail: (err) => {
                console.log("接口出错", err);
                reject(err);
            },
        });
    });
}

export function $get(url, data, needAuth = true) {
    return $request({ method: "GET", url, data, needAuth, });
}

//将参数放到路径中
export function $postQ(url, data, needAuth = true) {
    let qs = _.convertObj2Str(data);
    if (qs) url += "?" + qs;
    return $request({ method: "POST", url, needAuth });
}

//将参数放到body中
export function $postB(url, data, needAuth = true) {
    return $request({ method: "POST", url, data, needAuth });
}

//将参数放到form中
export function $postF(url, data, needAuth = true) {
    return $request({
        method: "POST",
        url,
        data,
        needAuth,
        header: {
            "content-type": "application/x-www-form-urlencoded",
        },
    });
}

export function $put(url, data, needAuth = true) {
    return $request({
        method: "PUT",
        url,
        data,
        needAuth,
    });
}

export function $del(url, data, needAuth = true) {
    return $request({
        method: "DELETE",
        url,
        data,
        needAuth,
    });
}

export function $upload({
    filePath,
    url = config.UPLOAD_URL,
    name = 'file',
    category = 'default'
}) {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url,
            filePath,
            name,
            header: {
                [config.KEY_TOKEN]: $getToken(),
            },
            formData: {
                category
            },
            complete: ({ data }) => {
                try {
                    if (typeof data === "string") data = JSON.parse(data);
                    resolve(data);
                } catch (e) {
                    resolve(null);
                }
            },
            fail: (res) => {
                $msg("上传失败");
                reject(res)
            },
        });
    });
}

export function $log(content) {
    try {
        $postB('https://simbajs.com:9109/system/log', {
            platform: "qingyun",
            content: JSON.stringify(content)
        })
    } catch (e) {

    } finally {
        return true
    }
}
